package com.ml.rabbitmq.d_direct.old;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author xr-8
 * @create 2021-04-14 22:56
 */
public class Consumer {

    public static void main(String[] args) {
        threeConsumer();
    }


    public static String threeConsumer() {
        for (int i = 1; i < 4; i++) {
            new Thread(() -> {
                consumer();
            }, "queue"+i).start();
        }
       return "done";
    }

    public static void consumer(){
        //1创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
//        connectionFactory.setVirtualHost("/ ");

        final String queueName = Thread.currentThread().getName();
        Connection connection = null;
        Channel channel = null;
        try {
            //2创建连接Connection
            connection = connectionFactory.newConnection("生产者");
            //3通过连接获取通道Channel
            channel = connection.createChannel();
            //4定义接受消息的回调
            channel.basicConsume(queueName, true,
                    (s, delivery) -> System.out.println(queueName+"收到消息是：" + new String(delivery.getBody(), "UTF-8")),
                    s -> System.out.println(queueName+"接受失败了..."));

            System.out.println(queueName+"开始接受消息!");
            System.in.read();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7关闭通道
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            //8关闭连接
            if (Objects.nonNull(connection) && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
